Linux GDB调试C++程序

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 编译C++程序

要编译的C++程序如下,文件名为spiral_matrix.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
vector<int> spiralOrder(vector<vector<int> >& matrix) {
vector<int> result;
int rows = matrix.size();
if(rows == 0) {
return result;
}
int columns = matrix[0].size();
int total = rows * columns;
for(int i = 0, j = 0; result.size() < total; i++, j++) {
if(result.size() < total) {
// top
for(int k = j; k < columns - j; k++) {
result.push_back(matrix[i][k]);
}
}
if(result.size() < total) {
// right
for(int k = i + 1; k < rows - i; k++) {
result.push_back(matrix[k][columns - 1 - j]);
}
}
if(result.size() < total) {
// bottom
for(int k = columns - 2 - j; k >= j; k--) {
result.push_back(matrix[rows - 1 - i][k]);
}
}
if(result.size() < total) {
// left
for(int k = rows - 2 - i; k > i; k--) {
result.push_back(matrix[k][j]);
}
}
}
return result;
}
};

int main() {
Solution s;
vector<int> temp;
temp.push_back(6);
temp.push_back(9);
temp.push_back(7);
vector<vector<int> > matrix;
matrix.push_back(temp);
s.spiralOrder(matrix);
return 0;
}

使用g++进行编译,编译命令为g++ -g spiral_matrix.cpp -o test-g参数表示编译时加入调试信息。

2. GDB调试

执行命令gdb test进入调试:

1
2
3
4
5
6
7
8
9
10
11
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-100.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home1/irteam/line-brain/tianchi/acm/test...done.
(gdb)

输入命令list 10查看代码,list <line_number>表示查看某行代码附近的代码。list 10也可简写为l 10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(gdb) list 10
5 class Solution {
6 public:
7 vector<int> spiralOrder(vector<vector<int> >& matrix) {
8 vector<int> result;
9 int rows = matrix.size();
10 if(rows == 0) {
11 return result;
12 }
13 int columns = matrix[0].size();
14 int total = rows * columns;
(gdb) l 10
5 class Solution {
6 public:
7 vector<int> spiralOrder(vector<vector<int> >& matrix) {
8 vector<int> result;
9 int rows = matrix.size();
10 if(rows == 0) {
11 return result;
12 }
13 int columns = matrix[0].size();
14 int total = rows * columns;
如果有收获,可以请我喝杯咖啡!